package com.hohai.river.utils;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import feign.Response;
import lombok.Cleanup;
import lombok.SneakyThrows;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * 读取JSON文件
 */
public class JsonUtils {

	public static final String BUCKET = "river";

	public static final String FILE_NAME = "6f695bda92d44dadb58f6dfd5b3d4f59.json";

	/**
	 * 读取JSON文件流获取JSONObject
	 * @param path 文件路径，相对于resources
	 * @return JSONObject
	 */
	public static JSONObject getJSONObject(String path) {
		ClassPathResource resource = new ClassPathResource(path);
		JSONObject jsonObject = new JSONObject();
		try {
			if (resource.exists()) {
				@Cleanup
				InputStream inputStream = resource.getInputStream();
				Object object = JSON.parseObject(inputStream, JSONObject.class);
				if (object instanceof JSONObject) {
					jsonObject = (JSONObject) object;
				}
			}
		}
		catch (IOException e) {
			return jsonObject;
		}
		return jsonObject;
	}

	public static JSONObject getDefaultJSON() {
		return getJSONObject("json/indexTable.json");
	}

	public static JSONArray getJSONArray(String indexName, String level) {
		JSONObject json = getDefaultJSON();
		return json.getJSONObject(indexName).getJSONArray(level);
	}

	public static double getValue(String indexName, String level, Integer selfEvaluate) {
		JSONArray array = getJSONArray(indexName, level);
		return array.getDoubleValue(selfEvaluate);
	}

	public static double getValue(String jsonStr, String indexName, String level, Integer selfEvaluate) {
		return JSON.parseObject(jsonStr).getJSONObject(indexName).getJSONArray(level).getDoubleValue(selfEvaluate);
	}

	@SneakyThrows
	public static JSONObject getJsonObjectFromResponse(Response response) {
		String json = IoUtil.read(response.body().asReader(StandardCharsets.UTF_8));
		return JSON.parseObject(json, JSONObject.class);
	}

	public static double getValueFromResponse(Response response, String indexName, String level, Integer selfEvaluate) {
		JSONObject jsonObject = getJsonObjectFromResponse(response);
		return jsonObject.getJSONObject(indexName).getJSONArray(level).getDoubleValue(selfEvaluate);
	}

}
